package com.panasonic.web.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.panasonic.web.domain.cms.CmsUser;
import com.panasonic.web.service.ICmsUserService;
import com.panasonic.web.util.JavaMailService;
import com.panasonic.web.vo.CmsUserImportVo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @className: CmsUserDataListener
 * @description: TODO 类描述
 * @author: laiweifeng
 * @date: 2021/11/21
 **/
public class CmsUserDataListener implements ReadListener<CmsUserImportVo> {
    private static final int BATCH_COUNT = 100;
    private List<CmsUser> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private ICmsUserService cmsUserService;
    private String permissionIds;
    private Integer type;
    private Integer pan;
    private Long panId;
    private boolean send;
    private JavaMailService javaMailService;

    public CmsUserDataListener(ICmsUserService cmsUserService,JavaMailService javaMailService, String permission, Integer type, Integer pan, Long panId,boolean send) {
        this.cmsUserService = cmsUserService;
        this.permissionIds = permission;
        this.type = type;
        this.pan = pan;
        this.panId = panId;
        this.send = send;
        this.javaMailService = javaMailService;
    }

    @Override
    public void invoke(CmsUserImportVo data, AnalysisContext analysisContext) {

        cachedDataList.add(data.toCmsUser(permissionIds.split(","), type, pan, panId));
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            cmsUserService.insertBatchCmsUser(cachedDataList);
            if(send==true){
                cachedDataList.stream().forEach(s -> {
                    //发送创建成功邮件通知
                    javaMailService.sendCreateUserEmail(s,s.getPasswordCache(),1);
                });
            }

            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        cmsUserService.insertBatchCmsUser(cachedDataList);
        if(send==true){
            cachedDataList.stream().forEach(s -> {
                //发送创建成功邮件通知
                javaMailService.sendCreateUserEmail(s,s.getPasswordCache(),1);
            });
        }
    }
}
